﻿using AutoMapper;
using MediatR;
using MonentExam1013.Api.Write.Appliaction.Commond;
using MonentExam1013.Domain;
using MonentExam1013.ErrorCode;
using MonentExam1013.infrastrunceture;

namespace MonentExam1013.Api.Write.Appliaction.Commondhandler
{
    public class UserAddCommondHandler : IRequestHandler<UserAddCommond, ApiResult<int>>
    {
        private readonly IBaseIrepository<User> user;
        private readonly IMapper mapper;

        public UserAddCommondHandler(IBaseIrepository<User> user, IMapper mapper)
        {
            this.user = user;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UserAddCommond request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code=ApiEnum.增加成功;
            result.Msg=ApiEnum.增加成功.ToString();
            using(var tran= user.Context.Database.BeginTransaction())
            {
                try
                {
                    User users = mapper.Map<User>(request);
                    await user.Add(users);
                    tran.Commit();  
                    return await Task.FromResult(result);
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
           
        }
    }
}
